package com.winsdom.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winsdom.context.BaseContext;
import com.winsdom.domain.vo.FinishedTaskVO;
import com.winsdom.domain.vo.UnfinishedTaskVO;
import com.winsdom.entity.Category;
import com.winsdom.entity.ReadingTask;
import com.winsdom.exception.BaseException;
import com.winsdom.mapper.ReadingTaskMapper;
import com.winsdom.service.IReadingTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.winsdom.enums.RedisKey.METERREADING_BUILDING;


/**
 * <p>
 * 抄表任务表 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-05-12
 */
@Service
@Slf4j
public class ReadingTaskServiceImpl extends ServiceImpl<ReadingTaskMapper, ReadingTask> implements IReadingTaskService {
    @Autowired
    private ReadingTaskMapper readingTaskMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Page<UnfinishedTaskVO> getNotReading(Long pageNum, Long pageSize,Long buildingId) {
        List<Long> categoryIds = getCategoryIds(buildingId);

        Page<UnfinishedTaskVO> unfinishedTask = readingTaskMapper.getUnfinishedTask(new Page<>(pageNum, pageSize),categoryIds);
        return unfinishedTask;
    }
    @Override
    public Page<FinishedTaskVO> getFinished(Long pageNum, Long pageSize,Long buildingId) {
        List<Long> categoryIds = getCategoryIds(buildingId);

        Page<FinishedTaskVO> finishedTask = readingTaskMapper.getFinishedTask(new Page<>(pageNum, pageSize),categoryIds);
        return finishedTask;
    }

    public List<Long> getCategoryIds(Long buildingId) {
        // 获取当前账号信息
        Long userId = Long.valueOf(BaseContext.getCurrentId());
        if (userId == null) {
            throw new BaseException("该账号异常");
        }
        log.info("用户id：{}", userId);
        String cacheKey = METERREADING_BUILDING.getValue() + userId;
        List<Category> categories = null;
        try {
            // 从 Redis 获取缓存数据
            categories = (List<Category>) redisTemplate.opsForValue().get(cacheKey);
        } catch (Exception e) {
            log.error("从Redis获取楼盘数据失败: {}", e.getMessage(), e);
        }
        // 获取分类ID集合
        List<Long> categoryIds = new ArrayList<>();
        if(buildingId != null){
            categoryIds.add(buildingId);
        }else {
            categoryIds = categories.stream()
                    .map(Category::getId)
                    .collect(Collectors.toList());
        }
        return categoryIds;
    }




}